package com.cheetah.start.module.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheetah.start.common.base.result.Result;
import com.cheetah.start.module.system.domain.SysMenu;
import com.cheetah.start.module.system.mapper.SysMenuMapper;
import com.cheetah.start.module.system.domain.SysRealMenu;
import com.cheetah.start.module.system.service.SysMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 系统菜单服务
 *
 * @author Feel
 * @date 2021/08/22
 */
@Slf4j
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {
    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public List<SysRealMenu> menuList(int userId) {
        return sysMenuMapper.menuList(userId);
    }

    @Override
    public List<SysRealMenu> toMenu(List<SysRealMenu> sysRealMenus, String parentId) {
        List<SysRealMenu> list = new ArrayList<>();
        for (SysRealMenu menu : sysRealMenus) {
            if (parentId.equals(menu.getParentId().toString())) {
                menu.setChildren(toMenu(sysRealMenus, menu.getId().toString()));
                list.add(menu);
            }
        }
        return list;
    }

    @Override
    public Result enableOrDisable(Integer menuId, String enable) {
        UpdateWrapper<SysMenu> wrapper = new UpdateWrapper<>();
        wrapper.eq("menu_id", menuId)
                .set("enable", enable);
        boolean update = update(wrapper);
        return Result.decide(update, "更新成功", "更新失败");
    }

    @Override
    public void setPreFix(List<SysRealMenu> sysRealMenus, String suffix) {
        if (CollUtil.isNotEmpty(sysRealMenus)) {
            if (!StrUtil.SLASH.equals(suffix)) {
                for (SysRealMenu sysRealMenu : sysRealMenus) {
                    sysRealMenu.setHref(suffix + sysRealMenu.getHref());
                }
            }
        }
    }
}
